<?php
require 'models/hand_analyser.php';
class DirList{
	function ReadFolderDirectory($dir = "root_dir/here")
    {
        $listDir = array();
        if($handler = opendir($dir)) {
            while (($sub = readdir($handler)) !== FALSE) {
                if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                    if(is_file($dir."/".$sub)) {
                        $listDir[] = $sub;
                    }elseif(is_dir($dir."/".$sub)){
                        $listDir[$sub] = $this->ReadFolderDirectory($dir."/".$sub);
                    }
                }
            }   
            closedir($handler);
        }
        return $listDir;   
    } 
}
	session_start();
	$dir = new DirList();
	$userdir = './userfiles/'.$_SESSION['username'];
	$dirList = $dir->ReadFolderDirectory($userdir);
	$dates = array_keys($dirList);
	
	function calculateTableCssClass($handLog){
		//if it's a cash table roi > 0?
		$eventClass = ($handLog['tableStats']['roi'] < 0 ) ? 'lost' : 'won';
		//if its a STT how many players started
		//print_r($handLog['tableStats']);
		if(!empty($handLog['tableStats']['sttPosition'])){
			//how many runners?
			$runners = array_shift($handLog['hands']);
			//print_r($runners);
			$players = count($runners['Players']);
			$payoutPosition = 3;
			if($players <= 6){
				$payoutPosition = 2;
			}
			//was it a winner takes all?
			$eventClass = ($handLog['tableStats']['sttPosition'] <= $payoutPosition ) ? 'won' : 'lost';
			
		}
		return $eventClass;
	}
	//echo '<pre>'; print_r($dirList); echo '</pre>';
	/*
	var events = [
    { "EventID": 1, "StartDate": new Date(2009, 1, 12), "Title": "10:00 pm - EventTitle1", "URL": "#", "Description": "This is a sample event description", "CssClass": "Birthday" },
    { "EventID": 2, "Date": "2009-02-28T00:00:00.0000000", "Title": "9:30 pm - this is a much longer title", "URL": "#", "Description": "This is a sample event description", "CssClass": "Meeting" },
];
	*/
	if(isset($_SESSION['username'])){
		$handAnalyser = new HandAnalyser();
		//echo 'Cache version number is '.$handAnalyser->cacheVersion;
	$eventsJsonString = '[';
	foreach($dates as $key=>$date){
		$year = date('Y',strtotime($date));
		$month = date('m',strtotime($date))-1; //stupid javascript month from 0
		$day = date('d',strtotime($date));
		
		//echo $date;
		//watch for pokerstars email hand history text files
		if(!is_array($dirList[$date])){
			$textFilesToProcess[] = $dirList[$date];
			continue;
		}
		
		foreach($dirList[$date] as $id=>$table){
			if(substr($table,0,1) != "."){
				$eventClass = 'notProcessed';
				//is there a cache of hand information?
				$md5File = md5_file($userdir.'/'.$date.'/'.$table);
				if(file_exists($userdir.'/'.$date.'/.'.$md5File.'.txt')){
					$handLog = file_get_contents($userdir.'/'.$date.'/.'.$md5File.'.txt');
					$handLog = unserialize($handLog);
					if(isset($handLog['version']) && $handLog['version']==$handAnalyser->cacheVersion){
						//get the event class
						//echo '<pre>'; print_r($handLog); echo '</pre>';
						//$eventClass = ($handLog['tableStats']['roi'] < 0 ) ? 'lost' : 'won';
						$eventClass = calculateTableCssClass($handLog);
						$monthHandsSeen += $handLog['tableStats']['handsSeen'];
						$monthVPP += $handLog['tableStats']['vpp'];
						$monthPFR += $handLog['tableStats']['pfr'];
						
						$afTotal += $handLog['tableStats']['agression']['raise']+$handLog['tableStats']['agression']['bet']+$handLog['tableStats']['agression']['call'];
						$afRaise += $handLog['tableStats']['agression']['raise'];
						$afBet += $handLog['tableStats']['agression']['bet'];
						$afCall += $handLog['tableStats']['agression']['call'];
						
						
					$wtsd += $handLog['tableStats']['wtsd'];
					$wtsdw += $handLog['tableStats']['wtsdw'];
						//cash is roi positive
						//stt - is finishing position in the money
					}
					else{
						//version is out of date unlink the file
						@unlink($userdir.'/'.$date.'/.'.$md5File.'.txt');
					}
					//echo '<pre>'; 
						//print_r($handLog);
					//echo '</pre>';
				}
				
		$event = '{ "EventID" : '.($id+1).', "StartDate" : new Date('.$year.', '.$month.', '.$day.'), "Title": "'.str_replace('.txt','',$table).'", "URL" : "handHistory.php?date='.$date.'&table='.urlencode($table).'", "Description" : "'.str_replace('.txt','',$table).'", "CssClass" : "'.$eventClass.'"},';
		$eventsJsonString .= $event;
				if(strtotime($date)>$lastEventTimeStamp){
					$lastEventDate = ' new Date('.$year.', '.$month.', '.$day.')';
					$lastEventTimeStamp = strtotime($date);
				}
			}
		}
		
	}
	//drop the last comma
	$eventsJsonString = substr($eventsJsonString,0,-1);
	
	foreach($textFilesToProcess as $key=>$textFile){
		@$fp = fopen($userdir.'/'.$textfile,'r');
		if($fp){
			//process the text file - save each hand cache file in the correct date folder
		
		fclose($fp);
		}
		
	}
	
	$eventsJsonString .= ']';
	}
	
	if(isset($_REQUEST['date'])){
		$year = date('Y',strtotime($_REQUEST['date']));
		$month = date('m',strtotime($_REQUEST['date']))-1; //stupid javascript month from 0
		$day = date('d',strtotime($_REQUEST['date']));
		$lastEventDate =' new Date('.$year.', '.$month.', '.$day.')';		
	}
	//$calendarDate = (isset($_REQUEST['date'])) ? $_REQUEST['date'] : $lastEventDate;
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hand Analyser</title>
<link REL="SHORTCUT ICON" HREF="http://ron.motionlabclients.co.uk/pkrHands/favicon.ico">

<link rel="stylesheet" type="text/css" href="views/themes/default/css/jquery-ui/theme/ui.all.css">
<link rel="stylesheet" type="text/css" href="app/webroot/css/core.css">

<style type="text/css">
td.weekend{ background-color: #6CF;}
#jMonthCalendar .Event.lost{background-color: #cc0000; color:#FFF;}
#jMonthCalendar .Event.lost A{color:#FFF;}

#jMonthCalendar .Event.won{background-color:#3C3; color:#FFF;}

#allTimeStats{list-style-type: none;}
#allTimeStats li{display: inline;}
</style>


<script src="http://www.google.com/jsapi?key=ABQIAAAAdbZzzW6_p1p1VZBkc9LxYhQRazRz_hx3HcUsGZHFt1z3iV6UMhQyhI0iG0NiX4N6bc6haD8-jdJPyg" type="text/javascript"></script>
<script type="text/javascript">
		var initJquery = function(){google.load("jquery", "1.2");
		google.load("jqueryui", "1.5");
		} ; 
		try {initJquery(); } catch (e){ setTimeout("1000" , initJquery ); }
</script>
<script src="app/webroot/js/jquery-jMonthCalendar-plugin.js"></script>
<script src="app/webroot/js/jquery-bubblepuff.js"></script>

<script>
	$('document').ready(function(){
		var options = { onMonthChanged : function(){processHandHistory();}};
		var events = <?php echo $eventsJsonString; ?>;
		$.jMonthCalendar.Initialize(options, events);
		$.jMonthCalendar.ChangeMonth(<?php echo $lastEventDate;?>)
		processHandHistory();
	});
	
	function processHandHistory(){
		
		
		//console.debug($('.Event.notProcessed'));
		$('.Event.notProcessed').each(
		 function(){
			date = $(this).parent().attr('date').split('/');
			table = $('a',$(this)).html();
			theEvent = this;
			date[0] = (date[0].length == 1) ? '0'+date[0]: date[0]
			date[1] = (date[1].length == 1) ? '0'+date[1]: date[1]
			//console.debug(date[2]+date[0]+date[1]);
			//console.debug(table);
			
			$.ajax({
				url : 'ajaxTableStatus.php',
				async : false,
				data : {'date':date[2]+date[0]+date[1],'table':table+'.txt'},
				success: function(msg) {
					//console.debug(theEvent);
					$(theEvent).removeClass('notProcessed');
					$(theEvent).addClass(msg);
				}
			});
		 });
	}
</script>
</head>

<body>
<div id="login"><?php if(!isset($_SESSION['username'])){?>
<form name="login" action="login.php" method="post">
<label for="username">Enter your poker site username:</label> <input id="username" name="username" value=""/> <input type="submit" name="login" value="Login"/>
</form>
<?php } 
else{
	echo '<h2>'.$_SESSION['username']." <a href=\"logout.php\">logout</a> </h2>";

	if($monthHandsSeen!=0){
?></div>
<ul id="allTimeStats">
<li class="handsSeen">All Time:  Hands Seen <?php echo $monthHandsSeen; ?></li>
<li class="vpp">All Time:  VPIP <?php echo $monthVPP;?> (<?php echo number_format(($monthVPP/$monthHandsSeen)*100);?>%)</li>
<li class="pfr">All Time:  PFR <?php echo $monthPFR;?> (<?php echo number_format(($monthPFR/$monthHandsSeen)*100);?>%)</li>
<?php if($afTotal){ ?>
<li>Agression Factor: 
<?php
			$raisePCT =($afRaise/$afTotal*100);
			$betPCT =($afBet/$afTotal*100);
		    $callPCT =($afCall/$afTotal*100);
			$callPCT =($callPCT==0) ? 1 : $callPCT;
	
			echo number_format((($raisePCT + $betPCT) / $callPCT) ,1);
?>
</li>
<?php }//end agression factor ?>
<li>Showdown: WTSD: <?php echo $wtsd;?> WTSDW: <?php echo $wtsdw;?></li>
<br style="clear: both"/>
</div>
<?php
	}
}//logged in else
?>
<div id="jMonthCalendar"></div>
<div style="clear: both">&nbsp;</div>
<?php include('googleTracking.php');?>
</body>
</html>